package com.application.fabric.fabriccontrol.fabricinit.connect;

import com.application.fabric.fabriccontrol.config.AccountStatus;
import com.application.fabric.fabriccontrol.config.Accountpath;
import com.application.fabric.users.entity.ExtractToken;
import org.hyperledger.fabric.gateway.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.nio.file.Path;
import java.nio.file.Paths;

@Repository
public class Congateway {
     static  {
        System.setProperty("org.hyperledger.fabric.sdk.service_discovery.as_localhost", "true");
    }
    /*连接网关配置
    * */
    @Autowired
    private  Accountpath accountpath;

    @Autowired
    private ExtractToken extractToken;

    public  Gateway connect() throws Exception{
        System.out.println("-------------------------------------------------");
        System.out.println(accountpath.getWallet());
        System.out.println("-------------------------------------------------");
        // Load a file system based wallet for managing identities.
        Path walletPath = Paths.get(accountpath.getWallet());
        Wallet wallet = Wallets.newFileSystemWallet(walletPath);
        // load a CCP
        Path networkConfigPath = Paths.get(accountpath.getConnect());

        Gateway.Builder builder = Gateway.createBuilder();
//        builder.identity(wallet, extractToken.getUserid()).networkConfig(networkConfigPath).discovery(true);
        builder.identity(wallet, "appUser").networkConfig(networkConfigPath).discovery(true);
        return builder.connect();
    }


    @Autowired
    private AccountStatus accountStatus;

    /*初始化链码 由于后续操作需要链码 所以我们尝试返回 contract 为后续使用提供*/
    public Contract initstatus() throws Exception{
                Gateway gateway = connect();
                // get the network and contract
                Network network = gateway.getNetwork("mychannel");
                Contract contract = network.getContract("basic");
                return contract;

    }

    public  Contract initstatus02() throws Exception{
        Gateway gateway = connect();
        // get the network and contract
        Network network = gateway.getNetwork("mychannel");
        Contract contract = network.getContract("basic02");
        return contract;

    }

    public  Contract initstatus03() throws Exception{
        Gateway gateway = connect();
        // get the network and contract
        Network network = gateway.getNetwork("mychannel");
        Contract contract = network.getContract("basic05");
        return contract;

    }

    public  Contract initstatus04() throws Exception{
        Gateway gateway = connect();
        // get the network and contract
        Network network = gateway.getNetwork("mychannel");
        Contract contract = network.getContract("basic04");
        return contract;

    }
}
